//打开预约课程界面
function viewBooking(personId) {
    layer.open({
        type: 2 //Page层类型
        , area: ['95%', '95%']
        , title: ''
        , shade: 0.6 //遮罩透明度
        , maxmin: false //允许全屏最小化
        , anim: 1 //0-6的动画形式，-1不开启
        , content: '/student/booked/course/' + personId + '?tokenString='+$('#tokenString').val()
        , cancel: function () {
            window.location.reload(true);
        }
    });
}
//取消课程弹窗界面
function cancelCourseHtml(lessonId,isAutoChange) {
    $("[rel=popover]").popover('destroy');
    let popoverObj=$("#delpopover"+lessonId);
    let dataContent = "";
    //取消预约课程原因列表
    let url='/lesson/cancel/course/reason/list';
    $.post(url,{},function (result,status) {
        if (status==="success"){
            if (result.status>0){
                let reasonList=result.data;
                if(reasonList !=null && reasonList.length>0){
                    let reasonHtml = "";
                    reasonHtml += '<select id="reason" class="form-control input-sm" name="">';
                    reasonHtml +="<option value=''>请选择原因|choose the reason</option>";
                    for(let i = 0;i<reasonList.length;i++){
                        reasonHtml+="<option value='"+reasonList[i].id+"'>"+reasonList[i].reason+"</option>";
                    }
                    reasonHtml+='</select>';
                    dataContent='<div style="text-align: center;"><div style="margin-bottom:5px;">提示：取消课程将返还课时或E币</div>';
                    if (isAutoChange===true){
                        dataContent+='<div style="text-align: center;color: red;"><div style="margin-bottom:5px;">警示：取消本节课程将关闭对应班表</div>';
                    }
                    dataContent+=reasonHtml;
                    dataContent+="<hr/>"
                    dataContent+='<button type="button" class="btn btn-default" onclick="$(\'#delpopover'+lessonId+'\').popover(\'destroy\');">取消</button>&nbsp;&nbsp;';
                    dataContent+='<button type="button" class="btn btn-danger" onclick="cancelCourseSubmit('+lessonId+')">确认</button><div>';
                    //console.info(dataContent);
                    popoverObj.popover({
                        html : true ,
                        title: '<span style="font-weight:bold;">确定要取消本节预约课程吗？</span>',
                        content: dataContent,
                        placement: 'auto'
                    });
                    popoverObj.popover("show");
                }
            }else {
                layer.msg("获取取消课程原因失败",{icon:2})
            }
        }else {
            layer.msg("请求失败:"+status,{icon:2})
        }
    },"json");
}

//批量取消课程弹窗界面
function bathCancelCourseHtml(lessonId) {
    let dataContent = "";
    //取消预约课程原因列表
    let url='/lesson/cancel/course/reason/list';
    $.post(url,{},function (result,status) {
        if (status==="success"){
            if (result.status>0){
                let reasonList=result.data;
                if(reasonList !=null && reasonList.length>0){
                    let reasonHtml = "";
                    reasonHtml += '<select id="reason" class="form-control input-sm" name="">';
                    reasonHtml +="<option value=''>请选择原因|choose the reason</option>";
                    for(let i = 0;i<reasonList.length;i++){
                        reasonHtml+="<option value='"+reasonList[i].id+"'>"+reasonList[i].reason+"</option>";
                    }
                    reasonHtml+='</select>';
                    dataContent='<div style="text-align: center;"><div style="margin-bottom:5px;">提示：取消课程将返还课时或E币</div>';
                    dataContent+=reasonHtml;
                    dataContent+="<hr/>"
                    // dataContent+='<button type="button" class="btn btn-default" onclick="$(\'#delpopover'+lessonId+'\').popover(\'destroy\');">取消</button>&nbsp;&nbsp;';
                    // dataContent+='<button type="button" class="btn btn-danger" onclick="cancelCourseSubmit('+lessonId+')">确认</button><div>';
                    layer.confirm(dataContent, {
                        btn: ['确定','考虑一下'] //按钮
                    }, function(){
                        batchCancelCourseSubmit(lessonId);
                        return false;
                    }, function(){

                    });
                }
            }else {
                layer.msg("获取取消课程原因失败",{icon:2})
            }
        }else {
            layer.msg("请求失败:"+status,{icon:2})
        }
    },"json");
}

/**
 * 提交取消课程
 * @param lessonId 课程id
 */
function cancelCourseSubmit(lessonId){
    //console.info($("#reason").val());
    let reasonId = $("#reason").val();
    if(reasonId == null || reasonId=='' ){
        layer.msg("请选择原因|Please choose the reason");
        return false;
    }
    let url = $("#bookedUrl").val()+'/course/cancel/'+lessonId+'/'+$('#recorder').val()+'/0';
    let param={"cancelReasonId" :reasonId ,"tokenString": $('#tokenString').val(),"recordId": $('#recordId').val()};
    $.post(url,param,function (result,status) {
        if (status==="success") {
            if (result.status === 1) {
                $("[rel=popover]").popover('destroy');
                layer.msg("取消课程成功",{icon:1},function refreshList() {
                    //$("form").submit();
                    window.location.reload(true);
                });
            }else {
                layer.msg(result.msg,{icon:2})
            }
        }else {
            layer.msg("请求失败:"+status,{icon:2})
        }
    },"json");
}

//批量取消课程提交数据
function batchCancelCourseSubmit(lessonId){
    //console.info($("#reason").val());
    let reasonId = $("#reason").val();
    if(reasonId == null || reasonId=='' ){
        alert("请选择原因|Please choose the reason");
        return false;
    }
    let url = $("#bookedUrl").val()+'/course/cancel/'+lessonId+'/'+$('#recorder').val()+'/0';
    let param={"cancelReasonId" :reasonId ,"tokenString": $('#tokenString').val(),"recordId": $('#recordId').val()};
    $.post(url,param,function (result,status) {
        console.log(result)
        console.log(status)
        if (status==="success") {
            if (result.status === 1) {
                $("[rel=popover]").popover('destroy');
                layer.msg("取消课程成功",{icon:1},function refreshList() {
                    //$("form").submit();
                    window.location.reload(true);
                });
            }else {
                layer.msg(result.msg,{icon:2})
            }
        }else {
            layer.msg("请求失败:"+status,{icon:2})
        }
    },"json");
}

/**
 * 打开弹窗页面
 * @param obj
 */
function layerOpenChangeWindow(lessonId,studentLogin) {
    let url="/lesson/change/init/"+lessonId+"?tokenString="+$("#tokenString").val();
    layer.open({
        type: 2,
        title: studentLogin+" 课程信息变更",
        closeBtn: 1, //显示关闭按钮
        shade: [0],
        area: ['800px', '500px'],
        //offset: 'rb', //右下角弹出
        // time: 2000, //2秒后自动关闭
        anim: 2,
        content: [url, 'no'], //iframe的url，no代表不显示滚动条
        end: function() {
            if ($("#isRefresh").length>0){
                let isRefresh=$("#isRefresh").val();
                // alert(isRefresh === "true")
                if (isRefresh === "true"){
                    location.reload(true);
                }
            }
        }
    });
}

function layerOpenReturnWindow(lessonId,studentLogin) {
    let url="/lesson/return/class/"+lessonId+"?tokenString="+$("#tokenString").val();
    layer.open({
        type: 2,
        title: studentLogin+" 返还课时申请",
        closeBtn: 1, //显示关闭按钮
        shade: [1],
        area: ['95%', '95%'],
        maxWidth:'800px',
        //offset: 'rb', //右下角弹出
        // time: 2000, //2秒后自动关闭
        anim: 2,
        content: [url, 'yes'], //iframe的url，no代表不显示滚动条
        end: function() {

        }
    });
}

/**
 * 获得可约课的老师列表
 */
function getTeacher() {
    if ($("#orderId").val()===""){
        layer.msg("本节课程不存在，课程列表将自动刷新",{icon:2},function () {
            $(window.parent.document).find("#isRefresh").val(true);
            layerClose();
        })
        return;
    }
    let layerLoadIndex = layer.load();
    let obj=$("#teacherLogin");
    obj.empty();
    obj.selectpicker('refresh');
    let url=$("#bookedUrl").val()+"/course/teacher/list";
    let param={"strClassTime":$("#releaseTime").val(),"orderId":$("#orderId").val(),"tokenString":$("#tokenString").val()
        ,"levelId":$("#teacherLevel").val(),"teaSiteId":$("#teaSiteId").val(),"commonTeacher":$("#teacherDefault").val()
    };
    $.post(url,param,function (result,status) {
        if (status==="success") {
            if (result.status === 1) {
                $("#addAuto,#addTemAuto").hide();
                let teaList=result.data;
                if (teaList!=null && teaList.length>0){
                    let levalName="",dataObj,strHtml;
                    for (let i=0,j=teaList.length;i<j;i++){
                        dataObj=teaList[i];
                        if (levalName!=dataObj.levelName){
                            levalName=dataObj.levelName;
                            strHtml="<optgroup label=\""+levalName+"\" id='"+levalName+"'></optgroup>";
                            obj.append(strHtml);
                        }
                        if (dataObj.common===1){
                            strHtml="<option value='"+dataObj.lessonId+"' style='color: #ffb746;'>"+dataObj.loginName+" | "+dataObj.siteName+" [常] </option>";
                        }else {
                            strHtml="<option value='"+dataObj.lessonId+"'>"+dataObj.loginName+" | "+dataObj.siteName+"</option>";
                        }

                        obj.find("#"+levalName).append(strHtml);
                    }
                    obj.val("");
                    obj.selectpicker('refresh');
                }else {
                    layer.msg("没有找到符合要求的老师",{icon:2,time: 1000});
                    /*layer.confirm('没有找到符合要求的老师，是否加入自动调课计划？', {
                        btn: ['加入','考虑一下'] //按钮
                    }, function(){
                        //加入
                        addChangeAutoInfo();
                    }, function(){
                        //考虑一下
                        $("#addAuto,#addTemAuto").show();
                    });*/
                    $("#addAuto,#addTemAuto").show();
                }
            }else {
                layer.msg(result.msg,{icon:2})
            }
        }else {
            layer.msg("请求失败:"+status,{icon:2})
        }
        layer.close(layerLoadIndex);
    },"json");
}

function changeTeacher(value) {
    if(value !== '' && !isNaN(value)){
        $("#lcrid").show();
    }else{
        $("#reasonId").val("");
        $("#lcrid").hide();
    }
}

/**
 * 保存课程变更信息
 * @returns {boolean}
 */
function saveChangeInfo() {
    let newLessonId=$("#teacherLogin").val();
    let strClassTime=$("#releaseTime").val();
    if (strClassTime===null || strClassTime==="" || strClassTime.length!==19){
        layer.msg("请选择需要变更的课程时间",{icon:2})
        return false;
    }
    /*if (newLessonId===null || newLessonId===""){
        layer.msg("请选择需要变更的老师",{icon:2})
        return false;
    }*/

    let url=$("#bookedUrl").val()+"/course/save/change";
    let param={"lessonId":$("#lessonId").val(),"tokenString":$("#tokenString").val(),"newLessonId":newLessonId
        ,"classWayId":$("#classWayId").val(),"recorder":$("#recorder").val(),"recordId":$("#recordId").val(),"reasonId":$("#reasonId").val()
    };
    let loadIndex = layer.load();
    $.post(url,param,function (result,status) {
        if (status==="success") {
            if (result.status === 1) {
                layer.msg("课程修改成功",{icon:1,time:2000},function () {
                    //设置父页的属性值，以便刷新父页
                    $(window.parent.document).find("#isRefresh").val(true);
                    // alert($(window.parent.document).find("#isRefresh").val());
                    layerClose();
                })
            }else {
                layer.msg(result.msg,{icon:2})
            }
        }else {
            layer.msg("请求失败:"+status,{icon:2})
        }
        layer.close(loadIndex);
    },"json");
}

/**
 * 加入自动调课计划操作
 * @returns {boolean}
 */
function addChangeAutoInfo(){
    let lessonId=$("#lessonId").val();
    let newReleaseTime=$("#releaseTime").val();
    let reasonId=$("#reasonId").val();
    if(reasonId == null || reasonId==='' ){
        alert("请选择调课原因|Please choose the reason");
        return false;
    }
    let url="/class/change/auto/add/"+lessonId
    $.post(url,{"newReleaseTime": newReleaseTime,"reasonId": reasonId},function (result,status){
        if (status==="success") {
            if (result.status === 1) {
                $("#addAuto,#addTemAuto").hide();
                $(window.parent.document).find("#isRefresh").val(true);
                layer.msg("添加自动调课成功",{icon:1,time:2000},function () {
                    layerClose();
                    let refresh=$(window.parent.document).find("form");
                    if (refresh.length>0){
                        refresh.submit();
                    }
                })
            }else {
                $("#addAuto,#addTemAuto").show();
                layer.msg(result.errMsg,{icon:2})
            }
        }else {
            $("#addAuto,#addTemAuto").show();
            layer.msg("请求失败:"+status,{icon:2})
        }
    },"json");
}

/**
 * 加入自动调课计划操作
 * @returns {boolean}
 */
function addTemporaryChangeAutoInfo(){
    let lessonId=$("#lessonId").val();
    let reasonId=$("#reasonId").val();
    if(reasonId == null || reasonId==='' ){
        alert("请选择调课原因|Please choose the reason");
        return false;
    }
    let url=$("#bookedUrl").val().replace("/crm","")+"/auto/change/course/save/temporary/change"
    $.post(url,{"reasonId": reasonId,"lessonId":lessonId,"recorder":$('#recorder').val(),
        "recordId": $('#recordId').val(),"tokenString":$("#tokenString").val()},function (result,status){
        if (status==="success") {
            if (result.status === 1) {
                $("#lessonId").val(result.lessonId);
                addChangeAutoInfo();
            }else {
                $("#addAuto,#addTemAuto").show();
                layer.msg(result.errMsg,{icon:2})
            }
        }else {
            $("#addAuto,#addTemAuto").show();
            layer.msg("请求失败:"+status,{icon:2})
        }
    },"json");
}

//批量加入调课计划弹窗界面
function bathChangeCourseHtml(lessonId) {
    let dataContent = "";
    //取消预约课程原因列表
    let url='/lesson/change/course/reason/list';
    $.post(url,{},function (result,status) {
        if (status==="success"){
            if (result.status>0){
                let reasonList=result.data;
                if(reasonList !=null && reasonList.length>0){
                    let reasonHtml = "";
                    reasonHtml += '<select id="reasonId" class="form-control input-sm" name="reasonId">';
                    reasonHtml +="<option value=''>请选择调课原因|choose the reason</option>";
                    for(let i = 0;i<reasonList.length;i++){
                        reasonHtml+="<option value='"+reasonList[i].id+"'>"+reasonList[i].name+"</option>";
                    }
                    reasonHtml+='</select>';
                    //dataContent='<div style="text-align: center;"><div style="margin-bottom:5px;">提示：取消课程将返还课时或E币</div>';
                    dataContent+=reasonHtml;
                    dataContent+="<hr/>"
                    // dataContent+='<button type="button" class="btn btn-default" onclick="$(\'#delpopover'+lessonId+'\').popover(\'destroy\');">取消</button>&nbsp;&nbsp;';
                    // dataContent+='<button type="button" class="btn btn-danger" onclick="cancelCourseSubmit('+lessonId+')">确认</button><div>';
                    layer.confirm(dataContent, {
                        btn: ['确定','考虑一下'] //按钮
                    }, function(){
                        batchChangeCourseSubmit(lessonId);
                        return false;
                    }, function(){

                    });
                }
            }else {
                layer.msg("获取调课原因失败",{icon:2})
            }
        }else {
            layer.msg("请求失败:"+status,{icon:2})
        }
    },"json");
}

//批量加入自动调课计划
function batchChangeCourseSubmit(lessonId){
    let reasonId=$("#reasonId").val();
    if(reasonId == null || reasonId==='' ){
        alert("请选择调课原因|Please choose the reason");
        return false;
    }
    let url="/class/change/auto/batch/add"
    $.post(url,{"lessonId": lessonId,"reasonId": reasonId},function (result,status){
        if (status==="success") {
            if (result.status === 1) {
                layer.msg(result.msg,{icon:1,time:2000},function () {
                    //layerClose();
                    let refresh=$("form");
                    if (refresh.length>0){
                        refresh.submit();
                    }
                })
            }else {
                layer.msg(result.errMsg,{icon:2})
            }
        }else {
            layer.msg("请求失败:"+status,{icon:2})
        }
    },"json");
}

//关闭当前layer弹出层
function layerClose() {
    let index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    parent.layer.close(index); //再执行关闭
}